package customplugin.projects;



import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IPath; 








import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

import customplugin.natures.ProjectNature;

public class CustomProjectSupport {
	
//	public final static String appjs =  "/* SC API should be in order to test the behavior of Secure Container.\n" +
//	                                  "* To perform actions after OnDeviceReady(), edit the start() method. Do not forget to specify \n" +
//	                                  "* and implement onSuccess and onFailure callback functions e.g. : \n \n" +
//	                                  "* sc.sample.func(function(result) { \n" +
//	                                  "*		alert('manufacturer=' + result.device.manufacturer); \n" +
//	                                  "*       }, function(error) { \n" +
//	                                  "*			 alert('error'); \n" +
//	                                  "*		}, 'param1', true); \n" +
//	                                  " */ \n \n" +
//	                                  "function start() { \n" +
//	                                  "var sc = null; \n" +
//	                                  "sc = cordova.require('sc');} \n";
//	                                  
//	
//	public final static String corejs =  "// Common initialization code goes here \n \n" +
//            "function Initialize() { \n" +
//            "	document.addEventListener('deviceready', onDeviceReady, false); \n" +
//            " } \n \n" +
//            "function onDeviceReady() { \n" +
//            "setTimeout(start, 0); \n" +
//            "} \n \n" +
//            " function onPause() { //Handle the pause event TODO  \n" +
//            "} \n \n" +
//            " function onResume() { //Handle the resume event TODO \n" +
//            "}";
//	
//	
//	public final static String scjs =  "(function() { \n \n" +
//            "cordova.define('sc/env', function(require, exports, module) { \n \n" +
//            "	var env = { \n" +
//            "		getDeviceId : function(success, failure) { \n" +
//            "			success ('1234567890000000'); \n" +
//            " }, \n }; \n" +
//            " module.exports = env; \n" +
//            "}); \n \n" +
//            "cordova.define('sc', function(require, exports, module) { \n" +
//            " 	var sc = { \n" +
//            "		env : require('sc/env') \n" +
//            "	}; \n" +
//            "	module.exports = sc; \n" +
//            "}); \n" +
//            "})();";
            
	                                  


	
	
	public static IProject createProject(String projectName, URI location, String appId, String api, String groupId, String title, String build, String version, String url) {
        Assert.isNotNull(projectName);
        Assert.isTrue(projectName.trim().length() > 0);
 
        IProject project = createBaseProject(projectName, location, appId, api, groupId, title, build, version, url);
        try {
            addNature(project);
            String[] paths = { "img", "lib", "res/icon/android", "res/icon/ios", "string"}; //$NON-NLS-1$ //$NON-NLS-2$
            addToProjectStructure(project, paths, appId, api, groupId, title, build, version, url);
        } catch (CoreException e) {
            e.printStackTrace();
            project = null;
        }
        
 
        return project;
    }
 
    /**
     * Just do the basics: create a basic project.
     *
     * @param location
     * @param projectName
     */
    private static IProject createBaseProject(String projectName, URI location, String appId, String api, String groupId, String title, String build, String version, String url) {
        // it is acceptable to use the ResourcesPlugin class
        IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
 
        if (!newProject.exists()) {
            URI projectLocation = location;
            IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName());
            if (location != null && ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(location)) {
                projectLocation = null;
            }
 
            desc.setLocationURI(projectLocation);
            try {
                newProject.create(desc, null);
                if (!newProject.isOpen()) {
                    newProject.open(null);
                }
            } catch (CoreException e) {
                e.printStackTrace();
            }
        }
 
        return newProject;
    }
 
    private static void createFolder(IFolder folder) throws CoreException {
        IContainer parent = folder.getParent();
        if (parent instanceof IFolder) {
            createFolder((IFolder) parent);
        }
        if (!folder.exists()) {
            folder.create(false, true, null);
        }
    }

    
    /**
     * Create a folder structure with a parent root, overlay, and a few child
     * folders.
     *
     * @param newProject
     * @param paths
     * @throws CoreException
     */
    private static void addToProjectStructure(IProject newProject, String[] paths, String appId, String api, String groupId, String title, String build, String version, String url) throws CoreException {
    	String textindex;
    	String textman;
    	String applicationId = "application-id='sc.app."+ appId +"'";
    	String group = "";
    	String apiversion ="";
    	String titles ="";
    	String scapi="";
    	String cordovapi="";
    	String buildapp="build='" + build +"'";;
    	String versionapp="";
    	String[] imgsandroid = { "icon-hdpi.png", "icon-mdpi.png", "icon-xhdpi.png", "icon-xxhdpi.png", "icon-xxxhdpi.png"}; //$NON-NLS-1$ //$NON-NLS-2$
    	String[] imgsios = { "icon-57@2x.png", "icon-57.png", "icon-60.png", "icon-60@2x.png", "icon-72.png", "icon-72@2x.png", "icon-76.png", "icon-76@2x.png" }; //$NON-NLS-1$ //$NON-NLS-2$
    	String[] libs = { "core.js", "app.js", "conf.js", "hideconf.js"}; //$NON-NLS-1$ //$NON-NLS-2$
    	
    	
    	Bundle bundle = Platform.getBundle("HTML5Environment");
    	URL scjs = bundle.getEntry("resources/sc.js");
    	
    	for (String path : paths) {
            IFolder etcFolders = newProject.getFolder(path);
            createFolder(etcFolders);
            if (path.equals("res/icon/android"))
            {
            	for (String img : imgsandroid) {
            		try{
            		URL imgurl = bundle.getEntry("defaultandroid/" + img);
            		IFile imgfile = newProject.getFile(img);
            		InputStream inputFile =  imgurl.openConnection().getInputStream();
            		imgfile.create(inputFile, IResource.NONE, null);
            		IPath renamedPath = etcFolders.getFullPath().append(img);
            		imgfile.move(renamedPath, false, null);
            		}
            		catch (IOException e) {
                	    e.printStackTrace();
                	}
            		}
            	
            }
            if (path.equals("res/icon/ios"))
            {
            	for (String img : imgsios) {
            		try{
            		URL imgurl = bundle.getEntry("defaultios/" + img);
            		IFile imgfile = newProject.getFile(img);
            		InputStream inputFile =  imgurl.openConnection().getInputStream();
            		imgfile.create(inputFile, IResource.NONE, null);
            		IPath renamedPath = etcFolders.getFullPath().append(img);
            		imgfile.move(renamedPath, false, null);
               
            		}
            		catch (IOException e) {
                	    e.printStackTrace();
                	}
            		}
            	
            }
            if (path.equals("lib"))
            {
            	for (String lib : libs) {
            		try{
            		URL imgurl = bundle.getEntry("resources/" + lib);
            		IFile libfile = newProject.getFile(lib);
            		InputStream inputFile =  imgurl.openConnection().getInputStream();
            		libfile.create(inputFile, IResource.NONE, null);
            		IPath renamedPath = etcFolders.getFullPath().append(lib);
            		libfile.move(renamedPath, false, null);
                  
            		}
            		catch (IOException e) {
                	    e.printStackTrace();
                	}
            		}
            	
            }
        }
    		
    	
    	
    	if(!api.equals("default")){
    		scapi="sc-" + api +".js";
    		cordovapi = "cordova-" + api + ".js";
    		apiversion="api-version='" + api +"'";
    		textindex = "<!DOCTYPE html>\n" + 
				   "<html>\n" + 
				   "<head> \n" +
				   "<meta charset=utf-8> \n" +
				   "<meta http-equiv='cache-control' content='max-age=0' /> \n" + 
				   "<meta http-equiv='cache-control' content='no-cache' /> \n" +
				   "<meta http-equiv='pragma' content='no-cache' /> \n" +
				   "<script src='lib/hideconf.js'></script> \n" +
				   "<script src='lib/conf.js'></script> \n" +
				   "<script src='cordova-" + api + ".js'></script> \n" +
				   "<script src='lib/app.js'></script> \n" +
				   "<script src='lib/core.js'></script> \n " +
				   "<script src='sc-" + api +".js'></script> \n" +
				   "</head> \n" +
				   "<body onload='Initialize()'></body> \n" +
				   "</html>"; 
    	}
    		else{
    			scapi="sc.js";
    			cordovapi = "cordova.js";
    			textindex = "<!DOCTYPE html>\n" + 
    					   "<html>\n" + 
    					   "<head> \n" +
    					   "<meta charset=utf-8> \n" +
    					   "<meta http-equiv='cache-control' content='max-age=0' /> \n" + 
    					   "<meta http-equiv='cache-control' content='no-cache' /> \n" +
    					   "<meta http-equiv='pragma' content='no-cache' /> \n" +
    					   "<script src='lib/hideconf.js'></script> \n" +
    					   "<script src='lib/conf.js'></script> \n" +
    					   "<script src='cordova.js'></script> \n" +
    					   "<script src='lib/app.js'></script> \n" +
    					   "<script src='lib/core.js'></script> \n " +
    					   "<script src='sc.js'></script> \n" +
    					   "</head> \n" +
    					   "<body onload='Initialize()'></body> \n" +
    					   "</html>"; 
    			
    		}
    	
    	if(!groupId.equals(""))
    		group="group-id='" + groupId +"'";
    	
    	if(!title.equals(""))
    		titles="<title>" + title +"</title> \n";
    	
    	if(!version.equals(""))
    		versionapp="version='" + version +"'";
    
    	textman = "<?xml version='1.0' encoding='UTF-8'?> \n" +
    	"<manifest xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \n" +
    	"xmlns='http://sc.merm.nttdata.co.jp/MANIFEST' xsi:schemaLocation='http://sc.merm.nttdata.co.jp/MANIFEST ../MANIFEST.xsd' \n" +
    	applicationId + "\n" +
    	group + "\n" +
    	buildapp + "\n" +
    	versionapp + "\n" +
    	apiversion + "> \n" +
        titles + "\n" +
    	"<icon device='android'>res/icon/android/icon-${screen-density}.png</icon> \n" +
        "<icon device='iOS'>res/icon/ios/icon.png</icon> \n" +
    	" <url>index.html</url> \n" +
    	"</manifest>";
    	
    	try {
    		
    	       IFile cordova = newProject.getFile(cordovapi);
    	       IFile sc = newProject.getFile(scapi);
    	       InputStream inputStream =  new FileInputStream(url);
    	       InputStream inputSc =  scjs.openConnection().getInputStream();
    	       cordova.create(inputStream, IResource.NONE, null);
               sc.create(inputSc, IResource.NONE, null);
    		 
    	} catch (IOException e) {
    	    e.printStackTrace();
    	}
    	
        IFile index = newProject.getFile("index.html");
        IFile manifest = newProject.getFile("MANIFEST.xml");
       
        
      if (!index.exists() && !manifest.exists() ) {
          byte[] bytes = textindex.getBytes();
          byte[] bytman = textman.getBytes();   
          InputStream inx = new ByteArrayInputStream(bytes);
          InputStream man = new ByteArrayInputStream(bytman);
          index.create(inx, IResource.NONE, null);
          manifest.create(man, IResource.NONE, null);
          
          // Creation of build folder and copy manifest.xml
//          IFolder buildfolder = newProject.getFolder("build");
//          buildfolder.create(false, true, null);
//          IPath renamedPath = buildfolder.getFullPath().append("MANIFEST.xml");
//          manifest.move(renamedPath, false, null);
//          IFile renamedmanifest = buildfolder.getFile("MANIFEST.xml");
      
      
   
      }
    }
 
    private static void addNature(IProject project) throws CoreException {
        if (!project.hasNature("customplugin.projectNature")) {
            IProjectDescription description = project.getDescription();
            String[] prevNatures = description.getNatureIds();
            String[] newNatures = new String[prevNatures.length + 1];
            System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
            newNatures[prevNatures.length] = "customplugin.projectNature";
            description.setNatureIds(newNatures);
 
            IProgressMonitor monitor = null;
            project.setDescription(description, monitor);
        }
    }
}
